package com.isolation.harassed.view;

import com.isolation.harassed.R;
import com.isolation.harassed.view.PageIndexPanel.OnPageIndexChangedListener;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends FragmentActivity implements OnPageIndexChangedListener{

	/* package */Fragment[] pages; // fixme:考虑使用可变长度集合

	private Fragment mCurPage = null;
//	private long previousBackPress = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		this.pages = new Fragment[getResources().getStringArray(
				R.array.activity_titles).length];
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onSwitched(int resId) {
		int index = (resId == R.id.navigation_profile) ? 0
				: (resId == R.id.navigation_treat_call) ? 1
						: (resId == R.id.navigation_treat_msg) ? 2 : -1;
		if (index != -1) {
			onChangeIndex(index);
		}
	}

	/** 由底部导航 index 决定屏幕显示的页面 */
	private void onChangeIndex(int index) {
		Fragment page = null;
		if ((page = pages[index]) != null) {
			FragmentTransaction mCurTransaction = getSupportFragmentManager()
					.beginTransaction();
			if (mCurPage != null && mCurPage != page && mCurPage.isVisible()) {
				mCurTransaction.hide(mCurPage);
				mCurPage.setUserVisibleHint(false);
				mCurPage = null;
			}
			if (!page.isAdded()) {
				mCurTransaction.add(R.id.home_container, page);
			} else if (!page.isVisible()) {
				mCurTransaction.show(page);
			}
			mCurTransaction.commitAllowingStateLoss();
			this.mCurPage = page;
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					mCurPage.setUserVisibleHint(true);
				}
			}, 100);
		}
	}

	/*@Override
	public void onBackPressed() {
		if ((System.currentTimeMillis() - previousBackPress) > 2000) {
			Toast.makeText(this, getText(R.string.msg_system_exit),
					Toast.LENGTH_SHORT).show();
			previousBackPress = System.currentTimeMillis();
		} else {
			this.finish();
			((App) getApplication()).exit();
		}
	}*/
}
